package com.corpgovernment.organization.factory;

import com.corpgovernment.common.base.CommonException;
import com.corpgovernment.common.common.CorpBusinessException;
import com.corpgovernment.organization.constant.OrganizationResponseCodeEnum;
import com.corpgovernment.organization.service.impl.AbstractLoginService;
import com.google.common.collect.Maps;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.List;
import java.util.Map;
import java.util.Optional;

/**
 * @author jhxue
 * @create 2022-02-18-14:25
 */
@Component
public class LoginServiceFactory {


	@Autowired
	private List<AbstractLoginService> loginServiceList;

	private volatile Map<String, AbstractLoginService> loginServiceMap;

	@PostConstruct
	private void init() {
		Map<String, AbstractLoginService> loginServiceHashMap = Maps.newHashMapWithExpectedSize(loginServiceList.size());
		for (AbstractLoginService loginService : loginServiceList) {
			loginServiceHashMap.put(loginService.getLoginType(), loginService);
		}
		loginServiceMap = loginServiceHashMap;
	}

	public AbstractLoginService getLoginService(String loginType) {
		return Optional.ofNullable(loginServiceMap.get(loginType)).orElseThrow(() -> new CorpBusinessException(OrganizationResponseCodeEnum.NO_SUCH_LOGIN_SERVICE));
	}

}
